package com.guyan.controller;

import com.github.pagehelper.PageInfo;
import com.guyan.entity.Shipping;
import com.guyan.form.ShippingForm;
import com.guyan.service.ShippingService;
import com.guyan.vo.LayuiVo;
import com.guyan.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * ClassName： ShippingController
 * Date： 2021/6/10 22:59
 *
 * @author 孤焰
 * @version 1.0
 **/

@RestController
@RequestMapping("/shipping")
public class ShippingController {

    @Autowired
    private ShippingService shippingService;

    @GetMapping("/shippingList")
    public LayuiVo shippingList(@RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "10") Integer limit,
                                Integer userId) {
        PageInfo pageInfo = shippingService.shippingList(page, limit, userId);

        return LayuiVo.success(pageInfo.getTotal(), pageInfo.getList());
    }

    @PostMapping("/addShipping")
    public ResultVo addShipping(@RequestBody @Valid ShippingForm shippingForm, BindingResult bindingResult) {
        if (bindingResult.getErrorCount() > 0) {
            return ResultVo.error(7000, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        Shipping shipping = new Shipping();
        BeanUtils.copyProperties(shippingForm, shipping);

        return shippingService.addShipping(shipping);
    }

    @PostMapping("/updateShippingById")
    public ResultVo updateShippingById(@RequestBody Shipping shipping) {
        return shippingService.updateShippingById(shipping);
    }

    @PostMapping("/batchDelShipping")
    public ResultVo batchDelShipping(@RequestBody Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return ResultVo.error(5001, "未选择要删除的收货地址");
        }

        return shippingService.batchDelShipping(ids);
    }
}
